package top.yangbuyi.system.controller;

import com.alibaba.druid.util.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import top.yangbuyi.system.common.*;
import top.yangbuyi.system.config.GITHUB.GitHubConstant;
import top.yangbuyi.system.config.QQ.OAuthProperties;
import top.yangbuyi.system.domain.Loginfo;
import top.yangbuyi.system.domain.User;
import top.yangbuyi.system.service.LoginfoService;
import top.yangbuyi.system.service.UserService;

import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;

/**
 * description:  杨不易网站 :www.yangbuyi.top
 * program:  yangbuyi-erp-2020
 * ClassName:  GithubLoginController
 * create:  2020-07-02 14:06
 *
 * @author: yangbuyi
 * @since： JDK1.8
 **/

@RestController
@RequestMapping("api/github")
public class GithubLoginController {
      
      @Autowired
      private UserService userService;
      @Autowired
      private OAuthProperties qqProperties;
      @Autowired
      private LoginfoService loginfoService;
      
      //回调地址 /api/github/oauth2
      @RequestMapping("/oauth2")
      public void oauth2(String code, String state, HttpServletResponse response) throws Exception {
            System.out.println("getHub");
            if (!StringUtils.isEmpty(code) && !StringUtils.isEmpty(state)) {
                  try {
                        //拿到我们的code,去请求token
                        //发送一个请求到
                        String token_url = GitHubConstant.TOKEN_URL.replace("CODE", code);
                        //得到的responseStr是一个字符串需要将它解析放到map中
                        String responseStr = HttpsUtils.doGetHub(token_url);
                        // 调用方法从map中获得返回的--》 令牌
                        String token = HttpsUtils.getMap(responseStr).get("access_token");
                        
                        //根据token发送请求获取登录人的信息  ，通过令牌去获得用户信息
                        String userinfo_url = GitHubConstant.USER_INFO_URL.replace("TOKEN", token);
                        responseStr = HttpsUtils.doGetHub(userinfo_url);
                        
                        Map<String, String> responseMap = HttpsUtils.getMapByJson(responseStr);
                        responseMap.put("登陆成功", "success");
                        
                        // 进行Shiro认证等......
                        
                        // 这里进行 QQ登陆用户 添加新的用户
                        // 设置用户基本信息
                        //  GiteeDTO giteeDTO = new GiteeDTO();
                        
                        User user1 = this.userService.queryUserByLoginName(responseMap.get("login"));
                        User user = null;
                        String remoteAddr1 = WebUtils.getHttpServletRequest().getHeader("X-Forwarded-For");
                        if (user1 == null) {
                              user = new User();
                              user.setName(responseMap.get("login"));
                              user.setLoginname(responseMap.get("login"));
                              user.setSalt(MD5Utils.createUUID());
                              user.setType(Constant.USER_TYPE_NORMAL);
                              user.setPwd(MD5Utils.md5(Constant.DEFAULT_PWD, user.getSalt(), 2));
                              user.setSex(0);
                              user.setAvailable(Constant.AVAILABLE_TRUE);
                              user.setImgpath(responseMap.get("avatar_url"));
                              user.setRemark("GITHUB登陆-" + responseMap.get("login"));
                              user.setAddress("GITHUB登陆 - IP地址" + remoteAddr1);
                              user.setDeptid(47);
                              user.setHiredate(new Date());
                              user.setOrdernum(this.userService.queryUserMaxOrderNum() + 1);
                              // 进行保存用户
                              this.userService.saveUser(user);
                              
                              
                              // 设置默认的角色
                              User user2 = this.userService.queryUserByLoginName(user.getLoginname());
                              /**
                               * 保存角色
                               */
                              this.userService.saveUserRole(user2.getId(), Constant.QQ_ROLE_DEFAULT);
                              System.out.println(user);
                              
                        } else {
                              // 修改gitee
                              // 如果已经有用户了  重新录入头像
                              user1.setName(responseMap.get("login"));
                              user1.setLoginname(responseMap.get("login"));
                              user1.setSex(0);
                              user1.setAvailable(Constant.AVAILABLE_TRUE);
                              user1.setImgpath(responseMap.get("avatar_url"));
                              user1.setRemark("GITHUB登陆-" + responseMap.get("login"));
                              user1.setAddress("GITHUB登陆 - IP地址" + remoteAddr1);
                              this.userService.updateUser(user1);
                              
                        }
                        
                        // 获取主体
                        Subject subject = SecurityUtils.getSubject();
//                  SecurityUtils.getSubject().login(new UsernamePasswordToken(qqOpenidDTO.getOpenid(), Constant.DEFAULT_PWD));
                        
                        
                        // 进行Shiro认证
                        subject.login(new UsernamePasswordToken(responseMap.get("login"), Constant.DEFAULT_PWD));
                        
                        token = subject.getSession().getId().toString();
                        ActiveUser active = (ActiveUser) subject.getPrincipal();
                        
                        /* 写入登陆日志开始 */
                        Loginfo loginfo = new Loginfo();
                        // String remoteAddr = WebUtils.getHttpServletRequest().getHeader("X-Forwarded-For");
                        loginfo.setLoginip(remoteAddr1);
                        loginfo.setLoginname(responseMap.get("login"));
                        loginfo.setLogintime(new Date());
                        loginfoService.save(loginfo);
                        /* 写入登陆日志结束 */
                        System.out.println("Shiro认证成功");
                        System.out.println(token);
                        
                        
                        response.sendRedirect(qqProperties.getQQ().getRedirect_url_index_yby() + "?token=" + token + "&github=" + responseMap);
                        // 成功则登陆
                  } catch (Exception e) {
                        // 否则返回到登陆页面
                        response.sendRedirect(qqProperties.getQQ().getRedirect_url_login_yby());
                  }
            }
            
      }
      
}
